package org.example.service.impl;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.example.dto.User;
import org.example.service.UserService;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {



    //数据模拟
    Map<String, User> maps = new ConcurrentHashMap<>();

    @Override
    //添加缓存
    @CachePut(value = "users",key = "#user.getId()")   //key==user.id   value = user
    public void addUser(User user) {
        maps.put(String.valueOf(user.getId()), user);
        System.out.println("添加成功");
      //  return maps.get(String.valueOf(user.getId()));
    }

    @Override
    //查询
    @Cacheable(value="users",key = "#id")
    public void getUser(Integer id) {
        User user = maps.get(String.valueOf(id));
        System.out.println("查询用户：" + user);
    }

    @Override
    //查询
    @Cacheable(value="users")
    public void getUser1() {
        System.out.println("查询用户：" + maps);
    }


    //添加或修改
    @Override
    @CachePut(value = "users",key = "#user.getId()")
    public void updateUser(User user) {
        String key = String.valueOf(user.getId());
        if (maps.containsKey(key)) {
            maps.get(key).setId(user.getId());
            maps.get(key).setName(user.getName());
            maps.get(key).setPass(user.getPass());
            System.out.println("修改成功");
        } else {
            System.out.println("没有修改");
        }
    }

    @Override
    //删除
    @CacheEvict(value="users",key = "#id")
    public void deleteUser(Integer id) {
        String key = String.valueOf(id);
        if (maps.containsKey(key)) {
            maps.remove(key);
        }
        System.out.println("移除成功");
    }
}
